package com.example.practice3.web;

import com.example.practice3.domain.Course;
import com.example.practice3.domain.Student;
import com.example.practice3.repository.CourseRepository;
import com.example.practice3.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/StudentInfo")
public class DesignController {
    private Student s;
    private List<Course> checkList;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private CourseRepository courseRepository;


    @GetMapping("/StudentInfo")
    public String addStudentInfo(Model model){
        //跳转到学生个人信息页面
        Student s=new Student();
        model.addAttribute("StudentInfo",s);

        return "StudentInfo";
    }

    @GetMapping("/SelectCourse")
    public String selectCourse(@ModelAttribute("StudentInfo") Student student, Errors errors, Model model){

        if(errors.hasErrors()){
            return "StudentInfo";
        }


        //实例化学生对象
        s=new Student();
        s=student;


//        //添加课程
//        List<Course> courses=new ArrayList<>();
//        courses.add(new Course("语文"));
//        courses.add(new Course("数学"));
//        courses.add(new Course("英语"));
//        courses.add(new Course("物理"));
//        courses.add(new Course("化学"));
//        courses.add(new Course("生物"));

        List<Course> list=courseDao.queryCourses();

        model.addAttribute("StudentInfo",s);
        model.addAttribute("courses",courses);

        return "SelectCource";
    }

    @PostMapping("/SelectResult")
    public String SelectResult(Model model,HttpServletRequest request){
        checkList=new ArrayList<>();
        String[] checkCourses=request.getParameterValues("SelectCourses");
        for(int i=0;i<checkCourses.length;i++)
            checkList.add(new Course(checkCourses[i]));

        studentRepository.save(s);
        System.out.println(s);


        model.addAttribute("StudentInfo",s);
        model.addAttribute("courses",checkList);
        return "SelectResult";
    }
}

